﻿using RndMaterialDisposalService.Attrbutes;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace RndMaterialDisposalService.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public class SwaggerHostInfo : IDocumentFilter
    {
        private readonly IWebHostEnvironment webHostEnvironment;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_webHostEnvironment"></param>
        public SwaggerHostInfo(IWebHostEnvironment _webHostEnvironment)
        {
            webHostEnvironment = _webHostEnvironment;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="context"></param>
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {

#if !DEBUG
            if (webHostEnvironment.EnvironmentName == "Development")
            {
                swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "http://10.163.100.135:8078" } };
            }
            else if (webHostEnvironment.EnvironmentName == "Uat")
            {
                swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "http://10.163.100.130:8081" } };
            }
            else if (webHostEnvironment.EnvironmentName == "Production")
            {
                //根据生产具体调整
                swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "http://10.163.96.48:9713" } };
            } 
#endif

            foreach (var item in context.ApiDescriptions)
            {
                var actionDescriptor = item.ActionDescriptor as ControllerActionDescriptor;
                if (actionDescriptor!.MethodInfo.CustomAttributes.Any(p => p.AttributeType == typeof(SwaggerHiddenApiAttribute)))
                {
                    Console.WriteLine($"{actionDescriptor.ControllerTypeInfo.FullName}.{actionDescriptor.ActionName}");
                    string key = "/" + item.RelativePath;
                    if (key.Contains("?"))
                    {
                        int idx = key.IndexOf("?", System.StringComparison.Ordinal);
                        key = key.Substring(0, idx);
                    }
                    swaggerDoc.Paths.Remove(key);
                }
            }
        }
    }
}
